import { createRouter, createWebHashHistory } from 'vue-router'
export const routes = [
  {
    path: '/',
    name: 'home',
    label: '首页',
    component: () => import('@/views/HomeView.vue'),
    children: [
      // this.menus
      {
        label: '账户管理',
        path: 'manager',
        name: 'manager',
        component: () => import('@/views/manager/ManagerIndexView.vue'),
        children: [
          {
            label: '管理员列表',
            path: 'managerlist',
            name: 'managerlist',
            component: () => import('@/views/manager/ManagerListView.vue')
          }
        ]
      },
      {
        label: '轮播图管理',
        path: 'banner',
        name: 'banner',
        component: () => import('@/views/banner/BannerIndexView.vue'),
        children: [
          {
            label: '轮播图列表',
            path: 'bannerlist',
            name: 'bannerlist',
            component: () => import('@/views/banner/BannerListView.vue')
          },
          {
            label: '添加轮播图',
            path: 'banneradd',
            name: 'banneradd',
            component: () => import('@/views/banner/BannerAddView.vue')
          }
        ]
      }
    ]
  },
  {
    label: '登录',
    path: '/login',
    name: 'login',
    component: () => import('@/views/LoginView.vue')
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 需要采用前置路由守卫进行登录拦截判断
const isLogin = () => {
  return !!localStorage.getItem('token')
}
router.beforeEach((to) => {
  if (to.name === 'login') {
    // 访问登录的时候，如果已经登录了，直接回到首页即可
    if (isLogin()) {
      ElMessage('登录状态有效，不需要重复登录！')
      return {
        name: 'home'
      }
    }
  } else if (to.name === 'home') {
    // 访问首页的时候，如果没有登录，那么就跳转到登录界面
    if (!isLogin()) {
      return { name: 'login' }
    }
  }
})

export default router
